

var olMap1;
$(document).ready(function () {

    resizeMap();
    window.onresize = function () {
        resizeMap();
    };
    function resizeMap()
    {
        let height = window.innerHeight - 60 +'px';
        console.log("高度是:"+ height);
        $(".left").height(height);
        // $(".left").css("marginTop",60);
        $(".right").height(height);
        // $(".right").css("marginTop",60);
    }

    /**
     * 加载树
     * */

    refreshTree(initTree);

    /**
     * 加载openlayer底图
     * */
    addOpenLayer();

    /**
     * 设置数据面板和Option面板的div可拖动
     */
    addMove('panel-hydrology-hydraulics-property-value');
    addMove('panel-simulation-options');
    function addMove(id) {
        var oDiv=document.getElementById(id);
        oDiv.onmousedown=function(ev) {
            // console.log("初始  鼠标 x："+ev.clientX);
            // console.log("初始  鼠标 y："+ev.clientY);
            // console.log("初始  div x："+oDiv.offsetLeft);
            // console.log("初始  div y："+oDiv.offsetTop);
            var disX = ev.clientX - oDiv.offsetLeft;
            var disY = ev.clientY - oDiv.offsetTop;
            isDown = true;

            document.onmousemove = function (ev) {
                var l = ev.clientX - disX;
                var t = ev.clientY - disY;

                // console.log("移动  鼠标 x："+ev.clientX);
                // console.log("移动  鼠标 y："+ev.clientY);
                // console.log("移动  div x："+l);
                // console.log("移动  div y："+t);

                oDiv.style.left = l + 'px';
                oDiv.style.top = t + 'px';
                // console.log("移动后  div x："+oDiv.style.left);
                // console.log("移动后  div y："+oDiv.style.top);
            }
        }
        oDiv.onmouseup = function () {
            document.onmousemove = null;
        }
    }

});


var initTree = [
    {
        "text": "TitleNotes",
        "href": "#TitleNotes"
    },
    {
        "text": "Options",
        "href": "#Options"
    },
    {
        "text": "Climatology",
        "href": "#Climatology"
    },
    {
        "text": "Hydrology",
        "href": "#Hydrology",
        "nodes":[
            {
                "text": "RainGages",
                "href": "#RainGages"

            },
            {
                "text": "Subcatchments",
                "href": "#Subcatchments"
            }
        ]
    },
    {
        "text": "Hydraulics",
        "href": "#Hydraulics",
        "nodes": [
            {
                "text": "Nodes",
                "href": "#Nodes",
                "nodes": [
                    {
                        "text": "Junctions",
                        "href": "#Junctions"
                    },
                    {
                        "text": "Outfalls",
                        "href": "#Outfalls"

                    },
                    {
                        "text": "Dividers",
                        "href": "#Dividers"

                    },
                    {
                        "text": "StorageUnits",
                        "href": "#StorageUnits"

                    }
                ]
            },
            {
                "text": "Links",
                "href": "#Links",
                "nodes": [
                    {
                        "text": "Conduits",
                        "href": "#Conduits"
                    },
                    {
                        "text": "Pumps",
                        "href": "#Pumps"
                    },
                    {
                        "text": "Orifices",
                        "href": "#Orifices"
                    },
                    {
                        "text": "Weirs",
                        "href": "#Weirs"
                    },
                    {
                        "text": "Outlets",
                        "href": "#Outlets"
                    }
                ]
            },
            {
                "text": "Transects",
                "href": "#Transects"
            },
            {
                "text": "Controls",
                "href": "#Controls"
            }
        ]
    },
    {
        "text": "Quality",
        "href": "#Quality",
        "nodes":[
            {
                "text": "Pollutants",
                "href": "#Pollutants"
            },
            {
                "text": "Land Uses",
                "href": "#LandUses"
            }
        ]
    },
    {
        "text": "Curves",
        "href": "#Curves",
        "nodes":[
            {
                "text": "Control Curves",
                "href": "#ControlCurves"
            },
            {
                "text": "Diversion Curves",
                "href": "#DiversionCurves"
            },
            {
                "text": "Pump Curves",
                "href": "#PumpCurves"
            },
            {
                "text": "Rating Curves",
                "href": "#RatingCurves"
            },
            {
                "text": "Shape Curves",
                "href": "#ShapeCurves"
            },
            {
                "text": "Storage Curves",
                "href": "#StorageCurves"
            },
            {
                "text": "Tidal Curves",
                "href": "#TidalCurves"
            }
        ]
    },
    {
        "text": "Time Series",
        "href": "#TimeSeries"
    },
    {
        "text": "Time Patterns",
        "href": "#TimePatterns"
    },
    {
        "text": "Map Labels",
        "href": "#MapLabels"
    }
];
function refreshTree(tree) {
    $('#treeview').treeview({
        color: "#428bca",
        showBorder: true,
        data: tree,
        expandIcon: 'glyphicon glyphicon-chevron-right',
        collapseIcon: 'glyphicon glyphicon-chevron-down'
        // levels:2
    });
}
function addOpenLayer() {

     olMap1 = new ol.Map({
        // 设置地图图层
        layers: [
            // 创建一个使用Open Street Map地图源的瓦片图层
            new ol.layer.Tile({
                source: new ol.source.OSM()
            })
        ],
        // 设置显示地图的视图
        view: new ol.View({
            center: [0, 0],    // 定义地图显示中心于经度0度，纬度0度处
            zoom: 2,            // 并且定义地图显示层级为2

        }),
        // 让id为map的div作为地图的容器
        target: 'panel-map',

    });
}
/**
 * 检查文本框输入的坐标系信息格式
 */

function checkProjInfoFormat(projInfo) {
    var projMatcher;
    projMatcher = projInfo.match(/proj4.defs\("EPSG:(\d*)","(.+)"\);/);
    if(projMatcher == null)
    {
        return false;
    }
    return true;
}

$("#input-projection").off('change');
$("#input-projection").bind('input propertychange',function () {

    var divEle = document.getElementById("div-projection");
    var spanEle = document.getElementById("span-projection-success");
    if($("#input-projection").val() == null || $("#input-projection").val() == "")
    {
        divEle.setAttribute('class',"form-group has-feedback");
        spanEle.setAttribute("class","glyphicon form-control-feedback");
        return;
    }
    if(!checkProjInfoFormat($("#input-projection").val()))
    {
        divEle.setAttribute('class',"form-group has-feedback has-error");
        spanEle.setAttribute("class","glyphicon  glyphicon-remove form-control-feedback");
        // alert("wrong proj4js format.");
    }
    else {
        divEle.setAttribute('class',"form-group has-feedback has-success");
        spanEle.setAttribute("class","glyphicon glyphicon-ok form-control-feedback");
    }
    spanEle.style.display = "inline";

});
function parseProjInfo(projInfo) {
    var projCode;

    //proj4.defs("EPSG:2437","+proj=tmerc +lat_0=0 +lon_0=120 +k=1 +x_0=500000 +y_0=0 +ellps=krass +towgs84=15.8,-154.4,-82.3,0,0,0,0 +units=m +no_defs");
    projCode = projInfo.match(/"EPSG:(\S*)",/)[1];
    return projCode;
}
/**
 * 将geojson加载到地图上
 */
function addGeoJson2Map(geojson,centerX,centerY) {
    var panel_map=document.getElementById('panel-map');
    if(panel_map)
    {
        for(var i=panel_map.childNodes.length-1;i>=0;i--)
        {
            panel_map.removeChild(panel_map.childNodes[i]);
        }

    }
    var source = new ol.source.Vector({
        features: (new ol.format.GeoJSON()).readFeatures(geojson)
    });
    var vectorLayer = new ol.layer.Vector({
        source: source,
    });
    //获取用户定义的坐标系信息
    var projCode;
    var m_projInfo = $("#input-projection").val();
    //如果为空，则默认为 3857 坐标系
    if (m_projInfo == null || m_projInfo =="")
    {
        projCode = 'EPSG:3857';
    }
    else {
        // 提取投影码
        projCode = 'EPSG:' +  parseProjInfo(m_projInfo);
        //proj4.defs("EPSG:2437","+proj=tmerc +lat_0=0 +lon_0=120 +k=1 +x_0=500000 +y_0=0 +ellps=krass +towgs84=15.8,-154.4,-82.3,0,0,0,0 +units=m +no_defs");

        // 定义投影信息
        eval(m_projInfo);
        // 将定义的投影信息注册到ol中去
        ol.proj.proj4.register(proj4);
    }
    var m_projection = new ol.proj.Projection({
        code: projCode,
        extent:[-20026376.39,-15496570.74,20026376.39,18764656.23],
        units: 'm',
        axisOrientation: 'neu',
    });
    var olMap2 = new ol.Map({
        // 设置地图图层
        layers: [
            // 创建一个使用Open Street Map地图源的瓦片图层
            new ol.layer.Tile({
                source: new ol.source.OSM()
            }),
            vectorLayer
        ],
        // 设置显示地图的视图
        view: new ol.View({
            center: [0,0],    // 定义地图显示中心于经度0度，纬度0度处
            zoom:2,            // 并且定义地图显示层级为2
            projection:m_projection,
        }),
        // 让id为map的div作为地图的容器
        target: 'panel-map',
    });
    // olMap1.addLayer(vectorLayer);

    var selectClick = new ol.interaction.Select({
        condition: ol.events.condition.click
    });
    olMap2.addInteraction(selectClick);
    selectClick.on('select',function (event,feature) {
        var name=event.selected[0].values_.name;
        var titleClass= findFeatureOwner(name);
        judgeTitleAndShow(titleClass,name,null);
    });

    olMap2.getView().animate({
        center:[centerX,centerY],
        zoom:18,
        duration: 2000
    });

    // ol.proj.addProjection(projection_2437);

}

var titleArray=new Array();
titleArray[0]="left-item-raingages";
titleArray[1]="left-item-subcatchments";
titleArray[2]="left-item-junctions";
titleArray[3]="left-item-outfalls";
titleArray[4]="left-item-storageunits";
titleArray[5]="left-item-conduits";

function findFeatureOwner(name) {
        // TODO 预定义一个数组，根据这个数组进行查表，返回title的类别
        var titleClass;
        if(findRecordIndexByItemName(name,"gage",raingageArrayList) !=-1)
        {
            titleClass="left-item-RainGages";
            // treeRainGagesOnClick();
            return titleClass;
        }
        if(findRecordIndexByItemName(name,"subcatchment",subcatchmentArrayList) !=-1)
        {
            titleClass="left-item-Subcatchments";
            // treeSubcatchmentsOnClick();
            return titleClass;
        }
        if(findRecordIndexByItemName(name,"junction",junctionArrayList) !=-1)
        {
            titleClass="left-item-Junctions";
            // treeJunctionsOnClick();
            return titleClass;
        }
        if(findRecordIndexByItemName(name,"outfall",outfallArrayList) !=-1)
        {
            titleClass="left-item-Outfalls";
            // treeOutfallsOnClick();
            return titleClass;
        }
        if(findRecordIndexByItemName(name,"storage",storageArrayList) !=-1)
        {
            titleClass="left-item-StorageUnits";
            // treeStorageUnitsOnClick();
            return titleClass;
        }
        if(findRecordIndexByItemName(name,"conduit",conduitArrayList) !=-1)
        {
            titleClass="left-item-Conduits";
            // treeConduitsOnClick();
            return titleClass;
        }

    }

var titleArrayList=new Array();
var option;
var evaporation;
var raingageArrayList;
var subcatchmentArrayList;
var subareaArrayList;
var infiltrationArrayList;
var junctionArrayList;
var outfallArrayList;
var storageArrayList;
var conduitArrayList;
var xscetionArrayList;
var lossesArrayList;
var curveArrayList;
var timeseriesArrayList;
var report;
var tagArrayList;
var map;
var coordinateArrayList;
var verticeArrayList;
var polygonArrayList;
var symbolArrayList;

var geojson;

var inputJsonCopy;


/**
 * 根据数据条目的名称,显示不同的数据面板
 * @param titleClass
 * @param name
 * @param id
 */
function judgeTitleAndShow(hrefClass,name,id) {
    switch (hrefClass)
    {
        case "left-item-TitleNotes":
        {

            break;
        }
        case "left-item-Options":
        {
            listOptionsOnclick(id);
            break;
        }
        case "left-item-Climatology":
        {
            break;
        }
        case "left-item-RainGages":
        {
            var indexOfRaingageArray= findRecordIndexByItemName(name,"gage",raingageArrayList);
            var indexOfSymbolArray=findRecordIndexByItemName(name,"gage",symbolArrayList);
            listRainGagesOnClick(indexOfRaingageArray,indexOfSymbolArray);
            $("#panel-hydrology-hydraulics-property-value").show();
            break;
        }
        case "left-item-Subcatchments":
        {
            var indexOfSubcatchment= findRecordIndexByItemName(name,"subcatchment",subcatchmentArrayList);
            var indexOfSubarea=findRecordIndexByItemName(name,"subcatchment",subareaArrayList);
            var indexOfInfiltration=findRecordIndexByItemName(name,"subcatchment",infiltrationArrayList);
            var indexOfRaingage=findRecordIndexByItemName(name,"gage",raingageArrayList);
            listSubcatchmentsOnClick(indexOfSubcatchment,indexOfSubarea,indexOfInfiltration);
            $("#panel-hydrology-hydraulics-property-value").show();
            break;
        }
        case "left-item-Junctions":
        {
            var indexOfJunctionArray=findRecordIndexByItemName(name,"junction",junctionArrayList);
            var indexOfCoordinateArray=findRecordIndexByItemName(name,"node",coordinateArrayList);
            listJunctionsOnClick(indexOfJunctionArray,indexOfCoordinateArray);
            $("#panel-hydrology-hydraulics-property-value").show();
            break;
        }
        case "left-item-Outfalls":
        {
            var indexOfOutfallArray = findRecordIndexByItemName(name,"outfall",outfallArrayList);
            var indexOfCoordinateArray=findRecordIndexByItemName(name,"node",coordinateArrayList);
            listOutfallsOnClick(indexOfOutfallArray,indexOfCoordinateArray);
            $("#panel-hydrology-hydraulics-property-value").show();
            var indexOfCoordinateArray;
            break;
        }
        case "left-item-StorageUnits":
        {
            var indexOfStorageArray=findRecordIndexByItemName(name,"storage",storageArrayList);
            var indexOfCoordinateArray=findRecordIndexByItemName(name,"node",coordinateArrayList);
            listStoragesOnClick(indexOfStorageArray,indexOfCoordinateArray);
            $("#panel-hydrology-hydraulics-property-value").show();
            break;
        }
        case "left-item-Conduits":
        {
            var indexOfConduiteArray=findRecordIndexByItemName(name,"conduit",conduitArrayList);
            var indexOfLossesArray=findRecordIndexByItemName(name,"culvert",lossesArrayList);
            var indexOfXsectionArray=findRecordIndexByItemName(name,"link",xscetionArrayList);
            listConduitsOnClick(indexOfConduiteArray,indexOfLossesArray,indexOfXsectionArray);
            $("#panel-hydrology-hydraulics-property-value").show();
            break;
        }
        default:
            break;

    }

}

/**
 * 右边动态产生的数据面板的submit和cancel的点击事件
 */
$("#button-dataview-group-cancel").off('click');
$("#button-dataview-group-cancel").on('click',function () {
    $("#panel-hydrology-hydraulics-property-value").hide();

});

$("#button-dataview-group-submit").off('click');
$("#button-dataview-group-submit").on('click',function () {
    //先获取dataview的uid属性（唯一标识此dataview表示的类别：subcatchment/rangage...等）
    var uid=document.getElementById("dataview").getAttribute("uid");
    //切割字符串，第二个元素为所属类别，eg：listSubcatchmentsOnClick()函数中的list
    var dataviewClassArray=uid.split('-');
    var dataviewClass=dataviewClassArray[1];
    //eg：raingage-dataviewlistright-symbolArrayList-y_coord，0是所属类别，2是每个input框所属的数组对象，3是数组对象中的列名
    var inputArray=document.getElementById("dataview-list-right").getElementsByTagName("input");
    console.log(inputArray);
    var index;
    submitValue(inputArray);
    $("#panel-hydrology-hydraulics-property-value").hide();

});

/**
 * 提交数据面板中对应的数据
 * @param inputArray 数据面板中的数据数组
 */

function submitValue(inputArray) {

    console.log(inputJsonCopy);
    var indexOfElementInArray;
    var indexOfTagArray;
    var elementName;
    for(var i=0;i<inputArray.length;i++)
    {
        var inputIdStrArray=inputArray[i].id.split('-');
        //id数组长度小于4，说明目前尚不支持此属性值的修改
        if(inputIdStrArray.length<4)
        {
            continue;
        }
        var inputOwnerListName=inputIdStrArray[2];
        var fieldName=inputIdStrArray[3];
        if(i==0)
        {
            //获取当前显示修改的表的元素在其所属数组对象中的序号，例如rain在raingageArrayList中为0
            indexOfElementInArray=findRecordIndexByItemName(inputArray[i].value,fieldName,eval(inputOwnerListName));
            elementName=inputArray[i].value;
        }
        else if(fieldName=="x_coord" || fieldName=="y_coord")
        {
            continue;
        }
        else if(fieldName=="description")
        {
            for(var j=0;j<eval("inputJsonCopy."+inputOwnerListName+"["+indexOfElementInArray+"]"+"."+fieldName+".length");j++)
            {
                eval("inputJsonCopy."+inputOwnerListName+"["+indexOfElementInArray+"]"+"."+fieldName+"["+j+"]"+"=inputArray["+i+"]."+"value");
            }
        }
        else if(fieldName=="tagId")
        {
            //获取当前显示修改的表的元素在其所属数组对象中的序号，例如rain在raingageArrayList中为0
            indexOfTagArray=findRecordIndexByItemName(elementName,fieldName,eval(inputOwnerListName));
            if(indexOfTagArray==-1 && (inputArray[i].value!=null && inputArray[i].value!="" && inputArray[i].value!=undefined))
            {
                var category;
                switch(inputIdStrArray[0])
                {
                    case "raingage":
                        category="rain";
                        break;
                    case "subchachment":
                        category="Subcatch";
                        break;
                    case "junction":
                    case "outfall":
                    case "storage":
                        category="Node";
                        break;
                    case "conduit":
                        category="Link";
                        break;
                    default:
                        break;
                }
                var tagObj={tagId:elementName,content:inputArray[i].value,category:category};
                inputJsonCopy.tagArrayList.push(tagObj);
            }
            else if(indexOfTagArray!=-1)
            {
                if(inputArray[i].value==null || inputArray[i].value=="" || inputArray[i].value==undefined)
                {
                    inputJsonCopy.tagArrayList.splice(indexOfTagArray,1);
                }
                else
                {
                    inputJsonCopy.tagArrayList[indexOfTagArray].content=inputArray[i].value;
                }
            }
            else {}
        }
        else if(inputOwnerListName=="option")
        {
            eval("inputJsonCopy."+inputOwnerListName+"."+fieldName+"=inputArray["+i+"]."+"value");
        }
        else
        {
            console.log(eval("inputArray["+i+"]."+"value"));
            console.log(eval("inputJsonCopy."+inputOwnerListName+"["+indexOfElementInArray+"]"+"."+fieldName));
            eval("inputJsonCopy."+inputOwnerListName+"["+indexOfElementInArray+"]"+"."+fieldName+"=inputArray["+i+"]."+"value");
        }
    }
    console.log(inputJsonCopy);
}

/**
 * 根据每个数据条目中的名字查找条目的序号
 * */
function findRecordIndexByItemName(itemName,field,array) {
    var index=-1;
    for (var i=0;i<array.length;i++)
    {
        console.log(eval('array[i].'+field));
        if (itemName===eval('array[i].'+field))
            index=i;
    }
    console.log(array[index]);
    return index;

}


/**
 * Option面板的submit及cancel点击事件
 */
$("#button-option-submit").off('click');
$("#button-option-submit").on('click',function () {
    console.log(inputJsonCopy.option);
    //General
    inputJsonCopy.option.ignore_rainfall=$("#checkbox-rainfall-runoff").prop('checked')==true?"NO":"YES";
    inputJsonCopy.option.ignore_routing=$("#checkbox-flow-routing").prop('checked')==true?"NO":"YES";
    inputJsonCopy.option.allow_ponding=$("#checkbox-allow-ponding").prop('checked')==true?"YES":"NO";
    inputJsonCopy.option.controls=$("#checkbox-report-control-actions").prop('checked')==true?"YES":"NO";
    inputJsonCopy.option.input=$("#checkbox-report-input-summary").prop('checked')==true?"YES":"NO";
    inputJsonCopy.option.min_slope=$("#input-minimum-conduit-slope").val();
    inputJsonCopy.option.infiltration=$("#div-option-general-infiltration-model input[type='radio']:checked").val();
    inputJsonCopy.option.flow_routing=$("#div-option-general-routing-model input[type='radio']:checked").val();
    //Dates
    inputJsonCopy.option.start_date=$("#input-option-dates-start-analysis-date").val();
    inputJsonCopy.option.start_time=$("#input-option-dates-start-analysis-time").val();
    inputJsonCopy.option.report_start_date=$("#input-option-dates-start-reporting-date").val();
    inputJsonCopy.option.report_start_time=$("#input-option-dates-start-reporting-time").val();
    inputJsonCopy.option.end_date=$("#input-option-dates-end-analysis-date").val();
    inputJsonCopy.option.end_time=$("#input-option-dates-end-analysis-time").val();
    inputJsonCopy.option.sweep_start=$("#input-option-dates-start-sweeping-date").val();
    inputJsonCopy.option.sweep_end=$("#input-option-dates-end-sweeping-date").val();
    inputJsonCopy.option.dry_days=$("#input-option-dates-antecedent-dry-days").val();
    //Time Steps
    var reportStepDays=$("#input-option-timesteps-reportstep-days").val();
    var reportStepTime=$("#input-option-timesteps-reportstep-time").val();
    var dryStepDays=$("#input-option-timesteps-drystep-days").val();
    var dryStepTime=$("#input-option-timesteps-drystep-time").val();
    var wetStepDays=$("#input-option-timesteps-wetstep-days").val();
    var wetStepTime=$("#input-option-timesteps-wetstep-time").val();
    var routingSeconds=$("#input-option-timesteps-routing-steps").val();

    inputJsonCopy.option.report_step=generateTimeSteps(reportStepDays,reportStepTime);
    inputJsonCopy.option.dry_step=generateTimeSteps(dryStepDays,dryStepTime);
    inputJsonCopy.option.wet_step=generateTimeSteps(wetStepDays,wetStepTime);
    inputJsonCopy.option.routing_step=convSecs2HourMins(routingSeconds);
    inputJsonCopy.option.skip_steady_state=$("#checkbox-timesteps-skip-steady-flow").prop('checked')==true?"YES":"NO";
    inputJsonCopy.option.sys_flow_tol=$("#input-option-timesteps-system-flow-tolerance").val();
    inputJsonCopy.option.lat_flow_tol=$("#input-option-timesteps-lateral-flow-tolerance").val();

    //Dynamic Waves
    inputJsonCopy.option.inertial_damping=$("#div-option-dynamicwave-inertialterm input[type='radio']:checked").val();
    inputJsonCopy.option.normal_flow_limited=$("#div-option-dynamicwave-normalflowcriterion input[type='radio']:checked").val();
    inputJsonCopy.option.force_main_equation=$("#div-option-dynamicwave-forcemainequation input[type='radio']:checked").val();
    inputJsonCopy.option.skip_steady_state=$("#checkbox-option-dynamic-wave-use-varibale").prop('checked')==true?"YES":"NO";
    inputJsonCopy.option.variable_step=$("#input-option-dynamic-wave-adjusted-by").val();
    inputJsonCopy.option.lengthening_step=$("#input-option-dynamic-wave-time-step-for-conduit").val();
    inputJsonCopy.option.min_surfarea=$("#input-option-dynamic-wave-minimum-nodal-surface").val();
    inputJsonCopy.option.max_trials=$("#input-option-dynamic-wave-maximum-trials-per").val();
    inputJsonCopy.option.head_tolerance=$("#input-option-dynamic-wave-head-convergence-tolerance").val();

    $("#panel-simulation-options").hide();
    console.log(inputJsonCopy.option);
});
$("#button-option-cancel").click(function () {
    $("#panel-simulation-options").hide();
});

/**
 * 在Option面板的Time Step标签页中Reporting,Runoff Dry/Wet Weather选项,根据输入的天数和时间,计算出时间步长
 * @param days 用户输入的天数
 * @param time 用户输入的时间
 * @returns {string} 时间步长
 */
function generateTimeSteps(days,time) {
    var timeArray=time.split(':');
    var hour=timeArray[0];
    var min=timeArray[1];
    var sec=timeArray[2];
    var outputHour=parseInt(days*24)+parseInt(hour);
    return (outputHour+":"+min+":"+sec);
}

/**
 * 在Option面板的Time Step标签页中的Routing选项,根据秒数,转换成 小时:分钟:秒 格式
 * @param secs
 * @returns {string}
 */
function convSecs2HourMins(secs) {
    var hour=parseInt(secs/3600);
    var min=parseInt((secs-hour*3600)/60);
    var sec=secs-hour*3600-min*60;
    return (hour+":"+min+":"+sec);
}

/**查找每个数据对应的tag*/
function findTag(category,id) {
    for (var i=0;i<tagArrayList.length;i++)
    {
        if (category===tagArrayList[i].category)
        {
            if(id===tagArrayList[i].tagId)
                return tagArrayList[i].content;
        }
    }
    return null;
}

/**根据表里的一个字段值获取另一个字段的平均值*/
function getFieldAverageValue(arrayList,field1,value,field2) {
    var sum=0;
    var count=0;
    var avg;
    for (var i=0;i<arrayList.length;i++)
    {
        if (eval('arrayList[i].'+field1)===value)
        {

            sum= sum+eval('arrayList[i].'+field2);
            count++;
        }
    }
    avg=sum/count;
    return avg;
}

/**动态创建元素*/
function createElement(identifier,list) {
    var dataview=document.getElementById("dataview");
    dataview.setAttribute("uid","dataview-"+identifier);
    var leftlist=document.getElementById("dataview-list-left");
    var rightlist=document.getElementById("dataview-list-right");
    for (var i=0;i<list.length;i++) {
        //构建左边的属性栏
        var itemleft = document.createElement("a");
        itemleft.innerText = list[i].property;
        itemleft.setAttribute("class", "list-group-item");
        itemleft.id = identifier + "-dataviewlistleft-" + list[i].name;
        itemleft.setAttribute("style", "border-bottom-right-radius: 0;border-top-right-radius: 0;height:38px;border-bottom-left-radius: 0px;");
        leftlist.appendChild(itemleft);
        //构建右边的值栏
        if (list[i].dropdown === "false") {
            var itemright = document.createElement("div");
            itemright.setAttribute("class", "input-group");
            itemright.style.height = "38px";
            itemright.style.marginBottom = "-1px";

            var input = document.createElement("input");
            input.value = list[i].value;
            input.setAttribute("class", "form-control");
            input.type = "text";
            input.id = identifier + "-dataviewlistright-" + list[i].name;
            if(list[i].name!="" && list[i].name!=null && list[i].name!=undefined)
            {
                var valueTypeArray=list[i].name.split('-');
                var valueType=valueTypeArray[1];
                if(valueType=="x_coord" || valueType=="y_coord")
                {
                    input.setAttribute("disabled","true/disable");
                }
            }
            input.setAttribute("style", "border-bottom-left-radius: 0;border-top-left-radius: 0;height:38px;border-color: #ddd;border-width: 1px;");
            input.style.borderStyle = "solid";
            input.style.paddingTop = "10px";
            input.style.paddingBottom = "10px";
            input.style.marginBottom = "-1px";
            itemright.appendChild(input);
            rightlist.appendChild(itemright);
        }
        else if (list[i].dropdown === "true") {
            var itemright = document.createElement("div");
            itemright.setAttribute("class", "input-group");
            itemright.style.height = "38px";
            itemright.style.marginBottom = "-1px";

            var input = document.createElement("input");
            input.value = list[i].value;
            input.setAttribute("class", "form-control");
            input.type = "text";
            input.id = identifier + "-dataviewlistright-" + list[i].name;
            input.setAttribute("style", "border-bottom-left-radius: 0;border-top-left-radius: 0;height:38px;border-color: #ddd;border-width: 1px;");
            input.style.borderStyle = "solid";
            input.style.paddingTop = "10px";
            input.style.paddingBottom = "10px";
            input.style.marginBottom = "-1px";

            itemright.appendChild(input);

            var div = document.createElement("div");
            div.setAttribute("class", "input-group-btn");

            var button = document.createElement("button");
            button.setAttribute("class", "btn btn-default dropdown-toggle");
            button.setAttribute("data-toggle", "dropdown");
            button.style.height = "38px";

            var span = document.createElement("span");
            span.setAttribute("class", "caret");
            button.appendChild(span);

            var ul = document.createElement("ul");
            ul.setAttribute("class", "dropdown-menu pull-right");
            for (var j = 0; j < list[i].data.length; j++) {
                var li = document.createElement("li");
                li.setAttribute("class", "dropdown-li");
                var href = document.createElement("a");
                href.href = "#";
                href.innerText = list[i].data[j];
                li.appendChild(href);
                //TODO 点击下拉框中的内容选择
                ul.appendChild(li);
            }
            div.appendChild(button);
            div.appendChild(ul);
            itemright.appendChild(div);
            rightlist.appendChild(itemright);
        }
        else {
        }
    }


}

/**
 * 加载显示每个数据的具体面板
 */
function listRainGagesOnClick(indexOfRaingageArray,indexOfSymbolArray) {
    //清空父div
    $("#dataview-list-left").empty();
    $("#dataview-list-right").empty();

    var leftlist = document.getElementById("dataview-list-left");
    var rightlist = document.getElementById("dataview-list-right");
    var tag = findTag("Gage", raingageArrayList[indexOfRaingageArray].gage);
    var timeseries = new Array();
    for (var i = 0; i < timeseriesArrayList.length; i++) {
        timeseries[i] = timeseriesArrayList[i].timeseries;
    }

    //TODO tag的修改，目前设计不支持在线修改tag
    var list = [
        {"name":"raingageArrayList-gage","property": "Name", "value": raingageArrayList[indexOfRaingageArray].gage, "dropdown": "false"},
        {"name":"symbolArrayList-x_coord","property": "X-Coordinate", "value": symbolArrayList[indexOfSymbolArray].x_coord, "dropdown": "false"},
        {"name":"symbolArrayList-y_coord","property": "Y-Coordinate", "value": symbolArrayList[indexOfSymbolArray].y_coord, "dropdown": "false"},
        {"name":"raingageArrayList-description","property": "Description", "value": raingageArrayList[indexOfRaingageArray].description, "dropdown": "false"},
        {"name":"tagArrayList-tagId","property": "Tag", "value": tag, "dropdown": "false"},
        {
            "name":"raingageArrayList-format",
            "property": "Rain Format",
            "value": raingageArrayList[indexOfRaingageArray].format,
            "dropdown": "true",
            "data": ["INTENSITY", "VOLUME", "CUMULATIVE"]
        },
        {
            "name":"raingageArrayList-interval",
            "property": "Time Interval",
            "value": raingageArrayList[indexOfRaingageArray].interval,
            "dropdown": "true",
            "data": ["0:01", "0:05", "0:10", "0:15", "0:20", "0:30", "1:00", "3:00", "6:00", "12:00", "24:00"]
        },
        {
            "name":"raingageArrayList-scf","property": "Snow Catch Factor", "value": raingageArrayList[indexOfRaingageArray].scf, "dropdown": "false"},
        {
            "name":"raingageArrayList-datasource",
            "property": "Data Source",
            "value": raingageArrayList[indexOfRaingageArray].datasource,
            "dropdown": "true",
            "data": ["TIMESERIES", "FILE"]
        },
        {
            "name":"raingageArrayList-seriesname",
            "property": "Series Name",
            "value": raingageArrayList[indexOfRaingageArray].seriesname,
            "dropdown": "true",
            "data": timeseries
        },
        {"name":"raingageArrayList-filename","property": "File Name", "value": raingageArrayList[indexOfRaingageArray].filename, "dropdown": "false"},
        {"name":"raingageArrayList-stationid","property": "Station ID", "value": raingageArrayList[indexOfRaingageArray].stationid, "dropdown": "false"},
        {
            "name":"raingageArrayList-rainunits",
            "property": "Rain Units",
            "value": raingageArrayList[indexOfRaingageArray].rainunits,
            "dropdown": "true",
            "data": ["IN", "MM"]
        }
    ];
    createElement("raingage",list);

    $(".dropdown-menu").off('click','li');

    $(".dropdown-menu").on('click','li',function () {
        showSelectedDropdownli(this);
    });
}
function listSubcatchmentsOnClick(indexOfSubcatchmentArray,indexOfSubareaArray,indexOfInfiltrationArray) {
    //清空父div
    $("#dataview-list-left").empty();
    $("#dataview-list-right").empty()

    var leftlist=document.getElementById("dataview-list-left");
    var rightlist=document.getElementById("dataview-list-right");
    var tag=findTag("Subcatch",subcatchmentArrayList[indexOfSubcatchmentArray].subcatchment);

    var xCoordinate=getFieldAverageValue(polygonArrayList,"polygon",subcatchmentArrayList[indexOfSubcatchmentArray].subcatchment,"x_coord");
    var yCoordinate=getFieldAverageValue(polygonArrayList,"polygon",subcatchmentArrayList[indexOfSubcatchmentArray].subcatchment,"y_coord");

    var raingages=new Array();
    for (var i=0;i<raingageArrayList.length;i++)
    {
        raingages[i]=raingageArrayList[i].gage;
    }

    var list=[
        {"name":"subcatchmentArrayList-subcatchment","property":"Name","value":subcatchmentArrayList[indexOfSubcatchmentArray].subcatchment,"dropdown":"false"},
        {"name":"polygonArrayList-x_coord","property":"X-Coordinate","value":xCoordinate,"dropdown":"false"},
        {"name":"polygonArrayList-y_coord","property":"Y-Coordinate","value":yCoordinate,"dropdown":"false"},  //TODO
        {"name":"subcatchmentArrayList-description","property":"Description","value":subcatchmentArrayList[indexOfSubcatchmentArray].description,"dropdown":"false"},
        {"name":"tagArrayList-tagId","property":"Tag","value":tag,"dropdown":"false"},
        {"name":"subcatchmentArrayList-raingage","property":"Rain Gage","value":subcatchmentArrayList[indexOfSubcatchmentArray].raingage,"dropdown":"true","data":raingages},
        {"name":"subcatchmentArrayList-outlet","property":"Outlet","value":subcatchmentArrayList[indexOfSubcatchmentArray].outlet,"dropdown":"false"},
        {"name":"subcatchmentArrayList-area","property":"Area","value":subcatchmentArrayList[indexOfSubcatchmentArray].area,"dropdown":"false"},
        {"name":"subcatchmentArrayList-width","property":"Width","value":subcatchmentArrayList[indexOfSubcatchmentArray].width,"dropdown":"false"},
        {"name":"subcatchmentArrayList-slope","property":"% Slope","value":subcatchmentArrayList[indexOfSubcatchmentArray].slope,"dropdown":"false"},
        {"name":"subcatchmentArrayList-imperv","property":"% Imperv","value":subcatchmentArrayList[indexOfSubcatchmentArray].imperv,"dropdown":"false"},
        {"name":"subareaArrayList-n_imperv","property":"N-Imperv","value":subareaArrayList[indexOfSubareaArray].n_imperv,"dropdown":"false"},   //TODO
        {"name":"subareaArrayList-n_perv","property":"N-Perv","value":subareaArrayList[indexOfSubareaArray].n_perv,"dropdown":"false"},
        {"name":"subareaArrayList-s_imperv","property":"Dstore-Imperv","value":subareaArrayList[indexOfSubareaArray].s_imperv,"dropdown":"false"},
        {"name":"subareaArrayList-s_perv","property":"Dstore-Perv","value":subareaArrayList[indexOfSubareaArray].s_perv,"dropdown":"false"},
        {"name":"subareaArrayList-pctzero","property":"%Zero-Imperv","value":subareaArrayList[indexOfSubareaArray].pctzero,"dropdown":"false"},
        {"name":"subareaArrayList-routeto","property":"Subarea Routing","value":subareaArrayList[indexOfSubareaArray].routeto,"dropdown":"true","data":["OUTLET","IMPERVIOUS","PERVIOUS"]},
        {"name":"subareaArrayList-pctrouted","property":"Percent Routed","value":subareaArrayList[indexOfSubareaArray].pctrouted,"dropdown":"false"},
        {"name":"option-infiltration","property":"Infiltration","value":option.infiltration,"dropdown":"false"},
        {"property":"Groundwater","value":"NO","dropdown":"false"},                                          //TODO
        {"property":"Snow Pack","value":"","dropdown":"false"},                                              //TODO
        {"property":"LID Controls","value":0,"dropdown":"false"},                                            //TODO
        {"property":"Land Uses","value":0,"dropdown":"false"},                                               //TODO
        {"property":"Initial Buildup","value":"NONE","dropdown":"false"},                                    //TODO
        {"property":"Curb Length","value":0,"dropdown":"false"}                                              //TODO
    ];

    createElement("subchachment",list);

    $(".dropdown-menu").off('click','li');

    $(".dropdown-menu").on('click','li',function () {
        showSelectedDropdownli(this);
    });
}
function listJunctionsOnClick(indexOfJunctionArray,indexOfCoordinateArray) {
    //清空父div
    $("#dataview-list-left").empty();
    $("#dataview-list-right").empty();


    var tag = findTag("Node", junctionArrayList[indexOfJunctionArray].junction);

    var list = [
        {"name":"junctionArrayList-junction","property": "Name", "value": junctionArrayList[indexOfJunctionArray].junction, "dropdown": "false"},
        {"name":"coordinateArrayList-x_coord","property": "X-Coordinate", "value": coordinateArrayList[indexOfCoordinateArray].x_coord, "dropdown": "false"},
        {"name":"coordinateArrayList-y_coord","property": "Y-Coordinate", "value": coordinateArrayList[indexOfCoordinateArray].y_coord, "dropdown": "false"},
        {"name":"junctionArrayList-description","property": "Description", "value": junctionArrayList[indexOfJunctionArray].description, "dropdown": "false"},
        {"name":"tagArrayList-tagId","property": "Tag", "value": tag, "dropdown": "false"},
        {"name":"Inflows","property": "Inflows", "value": "NO", "dropdown": "false"},   //TODO 目前不支持Inflows
        {"name":"Treatment","property": "Treatment", "value": "NO", "dropdown": "false"},//TODO
        {"name":"junctionArrayList-invert","property": "Invert EI.", "value": junctionArrayList[indexOfJunctionArray].invert, "dropdown": "false"},
        {"name":"junctionArrayList-maxdepth","property": "Max. Depth", "value": junctionArrayList[indexOfJunctionArray].maxdepth, "dropdown": "false"},
        {"name":"junctionArrayList-initdepth","property": "Initial Depth", "value": junctionArrayList[indexOfJunctionArray].initdepth, "dropdown": "false"},
        {"name":"junctionArrayList-surdepth","property": "Surcharge Depth", "value": junctionArrayList[indexOfJunctionArray].surdepth, "dropdown": "false"},
        {"name":"junctionArrayList-aponded","property": "Ponded Area", "value": junctionArrayList[indexOfJunctionArray].aponded, "dropdown": "false"}

    ];

    createElement("junction", list);


    $(".dropdown-menu").off('click', 'li');

    $(".dropdown-menu").on('click', 'li', function () {
        showSelectedDropdownli(this);
    });


}
function listOutfallsOnClick(indexOfOutfallArray,indexOfCoordinateArray) {
    // TODO 当没有tag时，查询到的index为空
    //清空父div
    $("#dataview-list-left").empty();
    $("#dataview-list-right").empty()

    var timeseries = new Array();
    for (var i = 0; i < timeseriesArrayList.length; i++) {
        timeseries[i] = timeseriesArrayList[i].timeseries;
    }
    var tag = findTag("Node", outfallArrayList[indexOfOutfallArray].outfall);

    var list = [
        {"name":"outfallArrayList-outfall","property": "Name", "value": outfallArrayList[indexOfOutfallArray].outfall, "dropdown": "false"},
        {"name":"coordinateArrayList-x_coord","property": "X-Coordinate", "value": coordinateArrayList[indexOfCoordinateArray].x_coord, "dropdown": "false"},
        {"name":"coordinateArrayList-y_coord","property": "Y-Coordinate", "value": coordinateArrayList[indexOfCoordinateArray].y_coord, "dropdown": "false"},
        {"name":"outfallArrayList-description","property": "Description", "value": outfallArrayList[indexOfOutfallArray].description, "dropdown": "false"},
        {"name":"tagArrayList-tagId","property": "Tag", "value": tag, "dropdown": "false"},
        {"name":"outfallArrayList","property": "Inflows", "value": "NO", "dropdown": "false"},   //TODO
        {"name":"outfallArrayList","property": "Treatment", "value": "NO", "dropdown": "false"}, //TODO
        {"name":"outfallArrayList-invert","property": "Invert EI.", "value": outfallArrayList[indexOfOutfallArray].invert, "dropdown": "false"},
        {"name":"outfallArrayList-gated","property": "Tide Gate", "value": outfallArrayList[indexOfOutfallArray].gated, "dropdown": "false"},
        {"name":"outfallArrayList-type","property": "Type", "value": outfallArrayList[indexOfOutfallArray].type, "dropdown": "false"},
        {"name":"outfallArrayList-stagedata","property": "Fixed Stage", "value": outfallArrayList[indexOfOutfallArray].stagedata, "dropdown": "false"},
        {"name":"outfallArrayList","property": "Curve Name", "value": "", "dropdown": "false"},  //TODO
        {"name":"timeseriesArrayList-timeseries","property": "Series Name", "value": "", "dropdown": "true","data":timeseries}

    ];

    createElement("outfall", list);


    $(".dropdown-menu").off('click', 'li');

    $(".dropdown-menu").on('click', 'li', function () {
        showSelectedDropdownli(this);
    });


}
function listStoragesOnClick(indexOfStorageArray,indexOfCoordinateArray) {
    //清空父div
    $("#dataview-list-left").empty();
    $("#dataview-list-right").empty();

    var tag = findTag("Node", storageArrayList[indexOfStorageArray].storage);

    var list = [
        {"name":"storageArrayList-storage","property": "Name", "value": storageArrayList[indexOfStorageArray].storage, "dropdown": "false"},
        {"name":"coordinateArrayList-x_coord","property": "X-Coordinate", "value": coordinateArrayList[indexOfCoordinateArray].x_coord, "dropdown": "false"},
        {"name":"coordinateArrayList-y_coord","property": "Y-Coordinate", "value": coordinateArrayList[indexOfCoordinateArray].y_coord, "dropdown": "false"},
        {"name":"storageArrayList-description","property": "Description", "value": storageArrayList[indexOfStorageArray].description, "dropdown": "false"},
        {"name":"tagArrayList-tagId","property": "Tag", "value": tag, "dropdown": "false"},
        {"name":"storageArrayList","property": "Inflows", "value": "NO", "dropdown": "false"},   //TODO
        {"name":"storageArrayList","property": "Treatment", "value": "NO", "dropdown": "false"}, //TODO
        {"name":"storageArrayList-invert","property": "Invert EI.", "value": storageArrayList[indexOfStorageArray].invert, "dropdown": "false"},
        {"name":"storageArrayList-maxdepth","property": "Max. Depth", "value": storageArrayList[indexOfStorageArray].maxdepth, "dropdown": "false"},
        {"name":"storageArrayList-initdepth","property": "Initial Depth", "value": storageArrayList[indexOfStorageArray].initdepth, "dropdown": "false"},
        {"name":"storageArrayList-ponded","property": "Ponded Area", "value": storageArrayList[indexOfStorageArray].ponded, "dropdown": "false"},
        {"name":"storageArrayList-fevap","property": "Evap. Factor", "value": storageArrayList[indexOfStorageArray].fevap, "dropdown": "false"},  //TODO
        {"name":"storageArrayList-seepage_exist","property": "Seepage Exist", "value": storageArrayList[indexOfStorageArray].seepage_exist, "dropdown": "false"},
        {"name":"storageArrayList-seepage","property": "Seepage Loss", "value": storageArrayList[indexOfStorageArray].seepage, "dropdown": "false"}, //TODO
        {"name":"storageArrayList-shape","property": "Storage Curve", "value": storageArrayList[indexOfStorageArray].shape, "dropdown": "true","data":["TABULAR","FUNCTIONAL"]},
        {"name":"storageArrayList-param[0]","property": "Coefficient", "value": storageArrayList[indexOfStorageArray].param[0], "dropdown": "false"},
        {"name":"storageArrayList-param[1]","property": "Exponent", "value": storageArrayList[indexOfStorageArray].param[1], "dropdown": "false"},
        {"name":"storageArrayList-param[2]","property": "Constant", "value": storageArrayList[indexOfStorageArray].param[2], "dropdown": "false"},
        {"name":"storageArrayList-curvename","property": "Curve Name", "value": storageArrayList[indexOfStorageArray].curvename, "dropdown": "false"}

    ];

    createElement("storage", list);

    $(".dropdown-menu").off('click', 'li');
    $(".dropdown-menu").on('click', 'li', function () {
        showSelectedDropdownli(this);
    });


}
function listConduitsOnClick(indexOfConduiteArray,indexOfLossesArray,indexOfXsectionArray) {
    //清空父div
    $("#dataview-list-left").empty();
    $("#dataview-list-right").empty();

    var tag = findTag("Link", conduitArrayList[indexOfConduiteArray].conduit);
    var entry_loss_coeff=(indexOfLossesArray==-1)?"0":lossesArrayList[indexOfLossesArray].entry_loss_coeff;
    var exit_loss_coeff=(indexOfLossesArray==-1)?"0":lossesArrayList[indexOfLossesArray].exit_loss_coeff;
    var avg_loss_coeff=(indexOfLossesArray==-1)?"0":lossesArrayList[indexOfLossesArray].avg_loss_coeff;
    var seepage_loss_rate=(indexOfLossesArray==-1)?"0":lossesArrayList[indexOfLossesArray].seepage_loss_rate;
    var flap_gate=(indexOfLossesArray==-1)?"0":lossesArrayList[indexOfLossesArray].flap_gate;

    var list = [
        {"name":"conduitArrayList-conduit","property": "Name", "value": conduitArrayList[indexOfConduiteArray].conduit, "dropdown": "false"},
        {"name":"conduitArrayList-fromnode","property": "Inlet Node", "value": conduitArrayList[indexOfConduiteArray].fromnode, "dropdown": "false"},
        {"name":"conduitArrayList-tonode","property": "Outlet Node", "value": conduitArrayList[indexOfConduiteArray].tonode, "dropdown": "false"},
        {"name":"conduitArrayList-description","property": "Description", "value": conduitArrayList[indexOfConduiteArray].description, "dropdown": "false"},
        {"name":"tagArrayList-tagId","property": "Tag", "value": tag, "dropdown": "false"},
        {"name":"xscetionArrayList-shape","property": "Shape", "value": xscetionArrayList[indexOfXsectionArray].shape, "dropdown": "false"},
        {"name":"xscetionArrayList-geom1","property": "Max. Depth", "value": xscetionArrayList[indexOfXsectionArray].geom1, "dropdown": "false"},
        {"name":"conduitArrayList-length","property": "Length", "value": conduitArrayList[indexOfConduiteArray].length, "dropdown": "false"},
        {"name":"conduitArrayList-roughness","property": "Roughness", "value": conduitArrayList[indexOfConduiteArray].roughness, "dropdown": "false"},
        {"name":"conduitArrayList-inoffset","property": "Inlet Offset", "value": conduitArrayList[indexOfConduiteArray].inoffset, "dropdown": "false"},
        {"name":"conduitArrayList-outoffset","property": "Outlet Offset", "value": conduitArrayList[indexOfConduiteArray].outoffset, "dropdown": "false"},
        {"name":"conduitArrayList-initflow","property": "Initial Flow", "value": conduitArrayList[indexOfConduiteArray].initflow, "dropdown": "false"},
        {"name":"conduitArrayList-maxflow","property": "Maximum Flow", "value": conduitArrayList[indexOfConduiteArray].maxflow, "dropdown": "false"},
        {"name":"lossesArrayList-entry_loss_coeff","property": "Entry Loss Coeff.", "value": entry_loss_coeff, "dropdown": "false"},
        {"name":"lossesArrayList-exit_loss_coeff","property": "Exit Loss Coeff", "value": exit_loss_coeff, "dropdown": "false"},
        {"name":"lossesArrayList-avg_loss_coeff","property": "Avg. Loss Coeff", "value": avg_loss_coeff, "dropdown": "false"},
        {"name":"lossesArrayList-seepage_loss_rate","property": "Seepage Loss Rate", "value": seepage_loss_rate, "dropdown": "false"},
        {"name":"lossesArrayList-flap_gate","property": "Flap Gate", "value": flap_gate, "dropdown": "true","data":["YES","NO"]},
        {"name":"xscetionArrayList-culvertcode","property": "Culvert Code", "value": xscetionArrayList[indexOfXsectionArray].culvertcode, "dropdown": "false"}
    ];

    createElement("conduit", list);
    $(".dropdown-menu").off('click', 'li');

    $(".dropdown-menu").on('click', 'li', function () {
        showSelectedDropdownli(this);
    });


}
function listOptionsOnclick(id) {
    $("#panel-simulation-options").show();
    listOptionsGeneralOnClick();
    listOptionsDatesOnClick();
    listOptionsTimeStepsOnClick();
    listOptionsDynamicWaveOnClick();
    switch(id)
    {
        case "General":
            $('#option-tabs a[href="#option-general"]').tab('show');

            break;
        case "Dates":
            $('#option-tabs a[href="#option-dates"]').tab('show');
            
            break;
        case "TimeSteps":
            $('#option-tabs a[href="#option-time-steps"]').tab('show');

            break;
        case "DynamicWave":
            $('#option-tabs a[href="#option-dynamic-wave"]').tab('show');

            break;
        case "InterfaceFiles":
            $('#option-tabs a[href="#option-files"]').tab('show');
            break;
        case "Reporting":
            break;
        default:
            break;

    }
}
function listOptionsGeneralOnClick() {
    // 第一块
    $("#checkbox-rainfall-runoff").attr("checked",option.ignore_rainfall=="YES"?false:true);
    $("#checkbox-rainfall-dependent").attr("checked",false);
    $("#checkbox-snow-melt").attr("checked",false);
    $("#checkbox-groundwater").attr("checked",false);
    $("#checkbox-water-quality").attr("checked",false);
    $("#checkbox-flow-routing").attr("checked",option.ignore_routing =="YES"?false:true);
    // 第二块
    $("#checkbox-allow-ponding").attr("checked",option.allow_ponding =="YES"?true:false);
    $("#checkbox-report-control-actions").attr("checked",report.controls=="YES"?true:false);
    $("#checkbox-report-input-summary").attr("checked",report.input=="YES"?true:false);
    $("#input-minimum-conduit-slope").val(option.min_slope);
    // 第三块
    switch (option.infiltration)
    {
        case "HORTON":
            $("#radio-option-general-horton").attr("checked",true);
            break;
        case "MODIFIED_HORTON":
            $("#radio-option-general-modified-horton").attr("checked",true);
            break;
        case "GREEN_AMPT":
            $("#radio-option-general-green-ampt").attr("checked",true);
            break;
        case "CURVE_NUMBER":
            $("#radio-option-general-curve-number").attr("checked",true);
            break;
        default:
            break;
    }
    // 第四块
    switch (option.flow_routing)
    {
        case "STEADY":
            $("#radio-option-general-steady-flow").attr("checked",true);
            break;
        case "KINWAVE":
            $("#radio-option-general-kinematic-wave").attr("checked",true);
            break;
        case "DYNWAVE":
            $("#radio-option-general-dynamic-wave").attr("checked",true);
            break;
        default:
            break;
    }
}
function listOptionsDatesOnClick() {

    $('#input-option-dates-start-analysis-date').val(option.start_date);
    $('#input-option-dates-start-analysis-time').val(option.start_time);
    $('#input-option-dates-start-reporting-date').val(option.report_start_date);
    $('#input-option-dates-start-reporting-time').val(option.report_start_time);
    $('#input-option-dates-end-analysis-date').val(option.end_date);
    $('#input-option-dates-end-analysis-time').val(option.end_time);
    $('#input-option-dates-start-sweeping-date').val(option.sweep_start);
    $('#input-option-dates-end-sweeping-date').val(option.sweep_end);
    $('#input-option-dates-antecedent-dry-days').val(option.dry_days);
    // $('#input-option-dates-start-analysis-date').val(option.start_date);


}
function listOptionsTimeStepsOnClick() {
    var reportStep=parseTimeSteps(option.report_step);
    $('#input-option-timesteps-reportstep-days').val(reportStep.days);
    var reportTime=reportStep.hours+":"+reportStep.minutes+":"+reportStep.seconds;
    $('#input-option-timesteps-reportstep-time').val(reportTime);

    var dryStep=parseTimeSteps(option.dry_step);
    $('#input-option-timesteps-drystep-days').val(dryStep.days);
    var dryTime=dryStep.hours+":"+dryStep.minutes+":"+dryStep.seconds;
    $('#input-option-timesteps-drystep-time').val(dryTime);

    var wetStep=parseTimeSteps(option.wet_step);
    $('#input-option-timesteps-wetstep-days').val(wetStep.days);
    var wetTime=wetStep.hours+":"+wetStep.minutes+":"+wetStep.seconds;
    $('#input-option-timesteps-wetstep-time').val(wetTime);

    var routingStep=parseRoutingSteps(option.routing_step);
    var routingSeconds=parseInt(routingStep.hours*3600)+parseInt(routingStep.minutes*60)+parseInt(routingStep.seconds);
    $('#input-option-timesteps-routing-steps').val(routingSeconds);

    $("#checkbox-timesteps-skip-steady-flow").attr("checked",option.skip_steady_state=="YES"?true:false);
    $('#input-option-timesteps-system-flow-tolerance').val(option.sys_flow_tol);
    $('#input-option-timesteps-lateral-flow-tolerance').val(option.lat_flow_tol);
    
}
function listOptionsDynamicWaveOnClick() {
    switch (option.inertial_damping)
    {
        case "NONE":
            $("#radio-option-dyanmic-wave-keep").attr("checked",true);
            break;
        case "PARTIAL":
            $("#radio-option-dyanmic-wave-dampen").attr("checked",true);
            break;
        case "FULL":
            $("#radio-option-dyanmic-wave-ignore").attr("checked",true);
            break;
        default:
            break;
    }
    switch (option.normal_flow_limited)
    {
        case "SLOPE":
            $("#radio-option-dyanmic-wave-slope").attr("checked",true);
            break;
        case "FROUDE":
            $("#radio-option-dyanmic-wave-froude").attr("checked",true);
            break;
        case "BOTH":
            $("#radio-option-dyanmic-wave-both").attr("checked",true);
            break;
        default:
            break;
    }
    switch (option.force_main_equation)
    {
        case "H-W":
            $("#radio-option-dyanmic-wave-hazen").attr("checked",true);
            break;
        case "D-W":
            $("#radio-option-dyanmic-wave-darcy").attr("checked",true);
            break;
        default:
            break;
    }
    $("#checkbox-option-dynamic-wave-use-varibale").attr("checked",option.variable_step=="0"?true:false);
    $('#input-option-dynamic-wave-adjusted-by').val(option.variable_step);
    $('#input-option-dynamic-wave-time-step-for-conduit').val(option.lengthening_step);
    $('#input-option-dynamic-wave-minimum-nodal-surface').val(option.min_surfarea);
    $('#input-option-dynamic-wave-maximum-trials-per').val(option.max_trials);
    $('#input-option-dynamic-wave-head-convergence-tolerance').val(option.head_tolerance);





}
/**
 * 判断要加载的数据面板中有哪些需要下拉框的,如果有就创造并显示出来
 * @param el
 */
function showSelectedDropdownli(el) {
    console.log($(el));
    console.log($(el).parent().parent().parent().children(".form-control"));
    console.log($(el).children("a")[0]);
    $(el).parent().parent().parent().children(".form-control")[0].value=$(el).children("a")[0].innerText;
}


/**
 * 根据加载的time step中的Reporting,Runoff Dry/Wet Weather的time step秒数解析出天数和时分秒
 * @param time
 * @returns {Object}
 */
function parseTimeSteps(time) {
    var timeArray=time.split(':');
    timestep=new Object();
    timestep.days=parseInt(timeArray[0]/24);
    timestep.hours=timeArray[0]%24;
    timestep.minutes=timeArray[1];
    timestep.seconds=timeArray[2];
    return timestep;
}

/**
 * 根据加载的time step中的Routing的hh:mm:ss格式解析出时分秒数
 * @param time
 * @returns {Object}
 */
function parseRoutingSteps(time) {
    var timeArray=time.split(':');
    routingstep=new Object();
    routingstep.hours=timeArray[0];
    routingstep.minutes=timeArray[1];
    routingstep.seconds=timeArray[2];
    return routingstep;
}

/**
 * 控制option的标签页
 * */
$("#option-tabs").off('click','li');
$('#option-tabs').on('click','li',function () {
    $('#option-tabs li:last').tab('show');
});

/**
 * 日期时间
 * */
$('.form_date').datetimepicker({
    language:  'fr',
    weekStart: 1,
    todayBtn:  1,
    autoclose: 1,
    todayHighlight: 1,
    startView: 2,
    minView: 2,
    forceParse: 0
});
$('.form_time').datetimepicker({
    language:  'fr',
    weekStart: 1,
    todayBtn:  1,
    autoclose: 1,
    todayHighlight: 1,
    startView: 1,
    minView: 0,
    maxView: 1,
    forceParse: 0
});

//TODO 考虑是否去掉
/**
 * 解析option dates中的日期
 * */
function parseDate(date) {
    var dateArray=date.split('/');
    return dateArray;

}

/**
 * 将数据传回后台，跑模型
 * */
$('#button-map-runmodel').off('click');
$('#button-map-runmodel').on('click',function () {
    //等待动画
    waitModelRunning();
    runModel();
});
var resultUrl;
function runModel() {

    //发送修改好的数据到后台
    $.ajax({
        type:"post",
        url:"/webswmm/runModel",
        dataType:'json',
        contentType:"application/json;charset=UTF-8",
        data:JSON.stringify(inputJsonCopy),
        success:function (data) {
            removeLoading('test');
            showAlertDiologue("success","run");
            resultUrl=data;
        },
        error:function (data) {
            console.log(data);
            removeLoading('test');
            showAlertDiologue("fail","run");
        }
    });
}

/**
 * 加载等待
 */
function waitModelRunning() {
    $('body').loading({
        loadingWidth: 240,
        title: 'Please wait!',
        name: 'test',
        discription: 'Model is running',
        direction: 'column',
        type: 'origin',
        // originBg:'#71EA71',
        originDivWidth: 40,
        originDivHeight: 40,
        originWidth: 6,
        originHeight: 6,
        smallLoading: false,
        loadingMaskBg: 'rgba(0,0,0,0.2)'
    });
}

/**
 * 下载结果
 */
$("#button-map-download").off('click');
$("#button-map-download").on('click',function () {
    downloadResult();
});
function downloadResult() {
    for (var i in resultUrl)
    {
        window.open(resultUrl[i]);
    }
}

/**
 * 结果可视化
 */

$("#button-map-view").off('click');
$("#button-map-view").on('click',function () {
    window.open('visualization');
});
/**
 * 上传输入数据
 */
$("#button-submitInputData").off('click');
$("#button-submitInputData").on('click',function () {
    //proj4.defs("EPSG:2437","+proj=tmerc +lat_0=0 +lon_0=120 +k=1 +x_0=500000 +y_0=0 +ellps=krass +towgs84=15.8,-154.4,-82.3,0,0,0,0 +units=m +no_defs");
    if(document.getElementById("input-uploadfile").files[0]!=null)
    {
        var formData=new FormData(document.getElementById('form-uploadfile'));
        console.log(formData);
        $("#modal-openudx").modal('hide');
        console.log("sfhsdgfhsdgfhbdsnbfgvyegrytwe")
        console.log("sfhsdgfhsdgfhbdsnbfgvyegrytwe")
        console.log("sfhsdgfhsdgfhbdsnbfgvyegrytwe")
        $.ajax({
            type:"post",
            url:"/webswmm/uploadFile",
            data:formData,
            dataType:"text",
            async:true,
            processData: false,  // 告诉jQuery不要去处理发送的数据
            contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
            success:function (fileName) {
                showAlertDiologue("success","load");

                console.log(fileName);
                sendLocalFileName(fileName);
            },
            error:function () {
                showAlertDiologue("fail","load");
            }
        });
    }
});

/**跳转到在线制作udx的页面*/
$("#a-makeUdxOnline").off('click');
$("#a-makeUdxOnline").on('click',function () {
    window.open('udxMaker');
});


/**
 * 显示警告框
 **/
function showAlertDiologue(status,type) {
    var father=document.getElementById("div-alert-diologue");
    var div=document.createElement("div");
    switch(status)
    {
        case "success":
            div.setAttribute("class","alert alert-success");
            break;
        case "fail":
            div.setAttribute("class","alert alert-danger");
    }

    var a=document.createElement("a");
    a.setAttribute("href","#");
    a.setAttribute("class","close");
    a.setAttribute("data-dismiss","alert");
    a.innerText="x";
    div.appendChild(a);
    var strongText=document.createElement("strong");
    switch(status)
    {
        case "success":
            switch(type)
            {
                case "load":
                    strongText.innerText="Data loaded successfully!";
                    break;
                case "run":
                    strongText.innerText="Model run successfully!";
                    break;
                case "select":
                    strongText.innerText="Select model service successfully!";
                    break;
                case "migrate":
                    strongText.innerText="Migrate model service successfully!";
                    break;
                default:
                    break;
            }
            break;
        case "fail":
            switch(type)
            {
                case "load":
                    strongText.innerText="Data loading failed!";
                    break;
                case "run":
                    strongText.innerText="Failed to run model!";
                    break;
                case "select":
                    strongText.innerText="Failed to select model service!";
                    break;
                case "migrate":
                    strongText.innerText="Failed to migrate model service!";
                default:
                    break;
            }
            break;
        default:
            break;

    }

    div.appendChild(strongText);
    father.appendChild(div);

}
function makeTree() {
    $.ajax({
        type:"post",
        dataType:'JSON',
        contentType:"application/json;charset=UTF-8",
        // traditional:true,
        async:true,
        url:"/webswmm/loadTree",
        data:JSON.stringify({initTree:initTree}),
        success:function (newTree) {
            // 获取geojson
            console.log("这是新的JSON：")
            console.log(JSON.stringify(newTree) );
            refreshTree(newTree);
        }
    });
}
/**
 * 将后台拿到的上传文件名发送给后台，后台根据文件名解析输入文件，并将解析的json发送给前台，前台获取并解析json
 * 将从后台拿到的输入数据文件名再返回给后台,后台会根据文件名将它发送给模型容器进行计算
 * @param localFileName
 */
function sendLocalFileName(fileName) {
    $.ajax({
       type:"post",
       dataType:'JSON',
       async:true,
       url:"/webswmm/parseInputData",
       data:{fileName:fileName},
       success:function (data) {
           // 获取geojson
           var inputGeojson=data.geojson;

           var inputJson = eval(data.json);

           console.log("data:"+data);
           console.log("geojson:"+inputGeojson);
           console.log("jsonObj:"+inputJson);

           titleArrayList=inputJson.titleArrayList;
           option=inputJson.option;
           evaporation=inputJson.evaporation;
           raingageArrayList=inputJson.raingageArrayList;
           subcatchmentArrayList=inputJson.subcatchmentArrayList;
           subareaArrayList=inputJson.subareaArrayList;
           infiltrationArrayList=inputJson.infiltrationArrayList;
           junctionArrayList=inputJson.junctionArrayList;
           outfallArrayList=inputJson.outfallArrayList;
           storageArrayList=inputJson.storageArrayList;
           conduitArrayList=inputJson.conduitArrayList;
           xscetionArrayList=inputJson.xscetionArrayList;
           lossesArrayList=inputJson.lossesArrayList;
           curveArrayList=inputJson.curveArrayList;
           timeseriesArrayList=inputJson.timeseriesArrayList;
           report=inputJson.report;
           tagArrayList=inputJson.tagArrayList;
           map=inputJson.map;
           coordinateArrayList=inputJson.coordinateArrayList;
           verticeArrayList=inputJson.verticeArrayList;
           polygonArrayList=inputJson.polygonArrayList;
           symbolArrayList=inputJson.symbolArrayList;
           makeTree();
           var centerX=coordinateArrayList[0].x_coord;
           var centerY=coordinateArrayList[0].y_coord;
           addGeoJson2Map(inputGeojson,centerX,centerY);
           inputJsonCopy=inputJson;
           console.log(inputJsonCopy);
       }
    });
}

/**
 * 前台打开文件按钮的点击事件
 */
$("#button-map-openfile").off('click');
$("#button-map-openfile").on('click',function () {

    document.getElementById("input-uploadfile").click();
    $('#input-uploadfile').on('change',function () {
        $('#input-udxFileInput')[0].defaultValue = document.getElementById("input-uploadfile").files[0].name;
    });
});


$("#button-map-selectService").off('click');
$("#button-map-selectService").on('click',function () {
    var tableId = "table-SelectModelService";
    // var labelId = "label-SelectModelService";
    getModelServicesInfo(tableId);
});

function getModelServicesInfo(tableId) {
    $.ajax({
        type:"get",
        dataType:'JSON',
        contentType:"application/json;charset=UTF-8",
        // traditional:true,
        // async:true,
        url:"/webswmm/getModelServicesInfo",
        // data:JSON.stringify({initTree:initTree}),
        success:function (jsonStr) {
            console.log(jsonStr);
            var jsonObj = JSON.parse(JSON.stringify(jsonStr));
            createModelServiceTable(jsonObj,tableId);
        }
    });
}


function createModelServiceTable(jsonArray,tableId) {
    //TODO 应该保留此句，并解决第二次点击就不显示的问题
    $("#"+tableId).bootstrapTable('destroy');
    // $("#"+tableId+" tbody").empty();
    var tbody = document.getElementById(tableId);
    var tableJson = {};
    tableJson.columns = [{
        field: 'id',
        title: '#'
    }, {
        field: 'property',
        title: 'Property'
    }, {
        field: 'value',
        title: 'Value'
    }];
    tableJson.data = [];

    for (var i=0;i<jsonArray.length;i++)
    {
        // var label  = $("#"+labelId);
        // label.text(jsonArray[i].wrapperId);
        var index = 1;
        tableJson.data.push({
            id:index,
            property:"ModelServiceWrapperId",
            value:jsonArray[i].wrapperId
        });
        index++;
        var software = jsonArray[i].SoftwareConfigures;
        for (var j=0;j<software.length;j++)
        {
            for (var key in software[j])
            {
                var jsonObj = {
                    id:index,
                    property:key,
                    value:software[j][key]
                };
                index++;
                tableJson.data.push(jsonObj);
            }
        }
        var hardware = jsonArray[i].HardwareConfigures;
        for (var j=0;j<hardware.length;j++)
        {
            for (var key in hardware[j])
            {
                var jsonObj = {
                    id:index,
                    property:key,
                    value:hardware[j][key]
                };
                index++;
                tableJson.data.push(jsonObj);
            }
        }

    }
    console.log(tableJson);

    $("#"+tableId).bootstrapTable({
        columns:tableJson.columns,
        data:tableJson.data,
        pagination: true,
        pageSize:4,
        pageList: [5, 10],
        striped: true,
        uniqueId:"id"
    });
}


$("#button-submitService").off('click');
$("#button-submitService").on('click',function () {

    var tableId = "table-SelectModelService";
    // var tableData = $("#"+tableId).bootstrapTable('getData',{useCurrentPage:true});
    var row = $("#"+tableId).bootstrapTable('getRowByUniqueId',1);
    var serviceWrapperId = row.value;
    $("#modal-selectService").modal('hide');
    //发送修改好的数据到后台
    $.ajax({
        type:"post",
        url:"/webswmm/setServiceWrapperGuid",
        dataType:'text',
        contentType:"application/x-www-form-urlencoded",
        data:{serviceWrapperId:serviceWrapperId},
        success:function (data) {
            console.log(data);
            showAlertDiologue("success","select");
        },
        error:function (data) {
            console.log(data);
            showAlertDiologue("fail","select");

        }
    });

});

$("#button-map-migrateService").off('click');
$("#button-map-migrateService").on('click',function () {
    //向后台发出请求，获取可供迁移的模型服务容器信息
    $.ajax({
        type:"post",
        url:"/webswmm/getMigratoryModelServiceInfo",
        dataType:'JSON',
        contentType:"application/json;charset=UTF-8",
        success:function (jsonStr) {
            var jsonObj = JSON.parse(JSON.stringify(jsonStr));
            var fromTableId = "table-MigrateModelService-From";
            // var fromLabelId = "label-MigrateModelService-From";
            getModelServicesInfo(fromTableId);
            var toTableId = "table-MigrateModelService-To";
            // var toLabelId = "label-MigrateModelService-To";
            createModelServiceTable(jsonObj,toTableId);
            console.log(jsonStr);
        },
        error:function (data) {
            console.log(data);
        }
    });
});

$("#button-migrateService").off('click');
$("#button-migrateService").on('click',function () {
    var fromTableId = "table-MigrateModelService-From";
    var toTableId = "table-MigrateModelService-To";
    var fromWrapperId = $("#"+fromTableId).bootstrapTable('getRowByUniqueId',1).value;
    var toWrapperId = $("#"+toTableId).bootstrapTable('getRowByUniqueId',1).value;
    var migrationDTO = {};
    migrationDTO.fromModelServiceGuid = fromWrapperId;
    migrationDTO.toModelServiceGuid = toWrapperId;
    $.ajax({
        type:"post",
        url:"/webswmm/setModelServiceMigration",
        dataType:'JSON',
        data:JSON.stringify({fromWrapperId:fromWrapperId,toWrapperId:toWrapperId}),
        contentType:"application/json;charset=UTF-8",
        success:function (jsonStr) {
            showAlertDiologue("success","migrate");
            console.log(jsonStr);
            // showAlertDiologue("success","select");
        },
        error:function (data) {
            console.log(data);
            // showAlertDiologue("fail","select");
            showAlertDiologue("fail","migrate");
        }
    });
    $("#modal-migrateService").modal('hide');
});


